package com.ruoyi.integration.service.token.loaders;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.integration.config.DustServiceProperties;
import com.ruoyi.integration.service.token.TokenLoader;
import lombok.RequiredArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

@Component
@RequiredArgsConstructor
public class DustTokenLoader implements TokenLoader {

    private final DustServiceProperties dustServiceProperties;

    private final static Logger logger = LoggerFactory.getLogger(DustTokenLoader.class);

    private final WebClient webClient;
    @Override
    public String loadToken() {

        String url = dustServiceProperties.getAuth().getTokenUrl();

        String responseWithToken = webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block();

        // 解析JSON
        JSONObject responseJson = JSONObject.parseObject(responseWithToken);

        // 检查返回码
        int code = responseJson.getIntValue("code");
        if (code != 1000) {
            String message = responseJson.getString("message");
            logger.error("获取Token失败，返回码: {}, 消息: {}", code, message);
            throw new RuntimeException("调用Token接口失败: " + message);
        }

        // 从 data 对象中提取 token
        JSONObject data = responseJson.getJSONObject("data");
        if (data == null) {
            logger.error("响应中缺少 'data' 字段");
            throw new RuntimeException("Token响应格式错误，缺少'data'字段");
        }

        String token = data.getString("token");
        if (token == null || token.isEmpty()) {
            logger.error("响应中缺少 'token' 字段");
            throw new RuntimeException("Token响应格式错误，缺少'token'字段");
        }

        return token;
    }

    @Override
    public String getDeviceType() {
        return "dust-monitor";
    }
}
